//商品分类全局组件的小仓库
import {defineStore} from "pinia";
import {reqC1, reqC2, reqC3, reqGetAttrs, reqAddOrUpdateAttr, reqRemoveAttr} from "../../api/product/attr/attrApi.ts";
import {reqGetSpu} from "../../api/product/spu/spuApi.ts";
import type {T_AttrResponseData, T_CategoryResponseData} from "../../api/product/attr/type.ts";
import type {T_CategoryState} from "./type/type.ts";
import type {T_Attr} from "../../api/product/attr/type.ts";
import type {T_SpuResponseData} from "../../api/product/spu/type.ts";

let useCategoryStore = defineStore('Category', {
    state: (): T_CategoryState => {
        return {
            c1Arr: [],//一级分类数据
            c1Id: '',//用于存当前用户选中1级标签 id
            c2Arr: [],//存取对应一级分类下的二级分类数据
            c2Id: '',//用于存取当前用户选中的二级分类标签id
            c3Arr: [],//存取对应二级分类下三级分类标签的id
            c3Id: ''
        }
    },
    actions: {
        //分类ID相关方法
        //获取一级分类的方法
        async getC1() {
            let result: T_CategoryResponseData = await reqC1();
            if (result.code == 200) {
                this.c1Arr = result.data;
            }
        },
        //获取二级分类的方法
        async getC2() {
            let result: T_CategoryResponseData = await reqC2((this.c1Id) as number)
            if (result.code == 200) {
                this.c2Arr = result.data;
            }
        },
        //获取三级分类的方法
        async getC3() {
            let result: T_CategoryResponseData = await reqC3((this.c2Id) as number)
            if (result.code == 200) {
                this.c3Arr = result.data;
            }
        },

        //属性相关方法
        //获取给定分类标签下的属性值
        async getAttrs() {
            let result: T_AttrResponseData = await reqGetAttrs(this.c1Id as number, this.c2Id as number, this.c3Id as number)
            if (result.code == 200) {
                return result.data;
            } else {
                return Promise.reject(new Error('获取属性失败！'));
            }
        },
        //添加或修改属性值方法
        async addOrupdateAttr(attrParams: T_Attr) {
            let result: any = await reqAddOrUpdateAttr(attrParams);
            if (result.code == 200) {
                return 'ok';
            } else {
                return Promise.reject(new Error(attrParams.id ? "修改失败" : "添加失败"));
            }
        },
        //删除属性方法
        async removeAttrById(attrId: number) {
            let result: any = await reqRemoveAttr(attrId);
            if (result.code == 200) {
                return 'ok';
            } else {
                return Promise.reject(new Error("删除失败！"))
            }
        },


        //spu相关方法
        //获取三级分类下的spu
        async getSpus(pageNo: number, pageSize: number) {
            let result: T_SpuResponseData = await reqGetSpu(pageNo, pageSize, this.c3Id)
            if (result.code == 200) {
                return result;
            } else {
                return Promise.reject(new Error("获取数据失败！"))
            }
        }


    },

    getters: {}
})

export default useCategoryStore;